package com.blockchain.anti_counterfeiting.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;


public class Auth {
    private String uid, password,token;

    private static final long EXPIRATION_TIME = 3600 * 1000; //1H
    private static final String SECRET = "COM.P2PSECRET.AUTH";

    public Auth(String email, String password) {
        this.uid = email;
        this.password = password;
    }
    public Auth(String token) {
        this.token = token;
    }

    public String generateToken() {
        try{
            Date expiration = new Date(System.currentTimeMillis() + EXPIRATION_TIME);
            token = JWT.create()
                    .withIssuer("w3.huaqucha.cn")
                    .withClaim("uid",uid)
                    .withClaim("passwd",password)
                    .withExpiresAt(expiration)
                    .sign(Algorithm.HMAC512(SECRET));
        }catch(JWTCreationException e){
            throw new RuntimeException(e);
        }
        return token;
    }

    public boolean verifyToken() {
        try{
            JWTVerifier verifier = JWT.require(Algorithm.HMAC512(SECRET)).withIssuer("w3.huaqucha.cn").build();
            DecodedJWT decodedJWT = verifier.verify(token);
            this.uid = decodedJWT.getClaim("uid").asString();
            this.password = decodedJWT.getClaim("passwd").asString();
            return true;
        } catch (RuntimeException e){
            throw new RuntimeException(e);
//            return false;
        }
    }
}
